<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * 采用最新Thinkphp5助手函数特性实现单字母函数M D U等简写方式
 * ============================================================================
 * 订单以及售后中心
 * @author soubao 当燃
 *  @Date: 2016-12-20
 */
namespace app\home\controller;
use app\common\logic\SaleLogic;
use app\common\logic\SearchWordLogic;
use think\Page;
use think\Verify;
use think\Image;
use think\Db;

class Sale extends Base {
	public function index()
	{
		$cat_id = I('get.id/d');
        $minValue = I('get.minValue');
        $maxValue = I('get.maxValue');
        $brandType = I('get.brandType');
        $point_rate = tpCache('shopping.point_rate');
        $is_new = I('get.is_new', 0);
        $exchange = I('get.exchange', 0);
        $goods_where = array(
            'is_on_sale' => 1,  //是否上架
            'state' => 1
        );
        //积分兑换筛选
        $exchange_integral_where_array = array(array('gt', 0));
        // 分类id
        if (!empty($cat_id)) {
            $goods_where['cat_id'] = array('in', getCatGrandson($cat_id));
        }
        //新品
        if ($is_new == 1) {
            $goods_where['is_new'] = 'id';
        }
        $goods_list_count = M('sale')->where($goods_where)->count();   //总页数
        $page = new Page($goods_list_count, 15);
        $goods_list = M('sale')->where($goods_where)->limit($page->firstRow . ',' . $page->listRows)->select();
        $goods_category = M('sale_cate')->where(array('level' => 1))->select();

        $this->assign('goods_list', $goods_list);
        $this->assign('page', $page->show());
        $this->assign('goods_list_count', $goods_list_count);
        $this->assign('goods_category', $goods_category);//商品1级分类
        $this->assign('point_rate', $point_rate);//兑换率
        $this->assign('nowPage', $page->nowPage);// 当前页
        $this->assign('totalPages', $page->totalPages);//总页数
		return $this->fetch();
	}
    public function indexs()
    {
    	$hot_goods = $hot_cate = $cateList = $recommend_goods = array();
      /*  $sql = "select a.*,b.name from ".C('database.prefix')."sale as a left join ";*/
        $sql = "select a.id,a.sname,a.market_price,a.shop_price,a.original_img,a.parent_cat_id,a.cat_id,a.cat_ids,a.parent_id_path,b.name from ".C('database.prefix')."sale as a left join ";
        $sql .= C('database.prefix')."sale_cate as b on a.parent_cat_id=b.id where a.is_hot=1 and a.state=1 order by a.sort";//二级分类下热卖商品  
        $index_hot_goods = S('index_hot_goods');
        if(empty($index_hot_goods))
        {
            $index_hot_goods = Db::query($sql);//首页热卖商品
            S('index_hot_goods',$index_hot_goods,TPSHOP_CACHE_TIME);
        }
       
        if($index_hot_goods){
              foreach($index_hot_goods as $val){
                  $cat_path = explode('_', $val['parent_id_path']);
                  $hot_goods[$cat_path[1]][] = $val;
              }
        }   
        $hot_category = M('sale_cate')->where("is_hot=1 and level=3 and is_show=1")->cache(true,TPSHOP_CACHE_TIME)->select();//热门三级分类 
        foreach ($hot_category as $v){
            $cat_path = explode('_', $v['parent_id_path']);
            $hot_cate[$cat_path[1]][] = $v;
        } 
        foreach ($this->saletree as $k=>$v){
            if($v['is_hot']==1){
        		$v['hot_goods'] = empty($hot_goods[$k]) ? '' : $hot_goods[$k];
        		$v['recommend_goods'] = empty($recommend_goods[$k]) ? '' : $recommend_goods[$k];
        		$v['hot_cate'] = empty($hot_cate[$k]) ? array() : $hot_cate[$k];
        		$cateList[]=$goods_category_tree[] = $v;
        	}else{
                $goods_category_tree[] = $v;
            }
        }
/*        dump($cateList);exit;*/
        $this->assign('cateList',$cateList);
        $this->assign('goods_category_tree',$goods_category_tree);
        return $this->fetch();
    }
    
    /**
     * 商品详情页
     */
    public function goodsInfo()
    {
    	$goodsLogic = new SaleLogic();
        $goods_id = I("get.id/d"); 
        $goods = M('sale')->where('id',$goods_id)->find();
        if(empty($goods) || !$goods){
            $this->error('该商品已经下架', U('sale/index'));
        }
        $goods_images_list = M('sale_images')->where("goods_id", $goods_id)->select(); // 商品 图册
        $res['goods_id'] = $goods_id;
        $user = session('user');      
        $res['uid'] =  $user['user_id'];
        $res['state'] = 1;
        $cash = M('cash')->where($res)->find();
        $this->assign('goods_images_list',$goods_images_list);
        $this->assign('navigate_goods', navigate_goods_sale($goods_id, 1));// 面包屑导航
        $this->assign('goods',$goods);
        $this->assign('cash',$cash);
        //构建手机端URL
        $ShareLink = urlencode("http://{$_SERVER['HTTP_HOST']}/index.php?m=Mobile&c=sale&a=goodsInfo&id={$goods['id']}");
        $this->assign('ShareLink', $ShareLink);
        $this->assign('look_see', $goodsLogic->get_look_see($goods));//看了又看
        return $this->fetch();
    }

    /**
     * 商品列表页
     */
    public function goodslist()
    {

    	$key = md5($_SERVER['REQUEST_URI'] . I('start_price') . '_' . I('end_price'));
        $html = S($key);
        if (!empty($html)) {
            return $html;
        }

        $filter_param = array(); // 帅选数组    
        $id = I('get.id/d',1); // 当前分类id
        $price = I('get.price', ''); // 价钱
        $sort = I('sort', 'sort'); // 排序
        $sort_asc = I('sort_asc', 'desc'); // 排序
        $start_price = trim(I('post.start_price', '0')); // 输入框价钱
        $end_price = trim(I('post.end_price', '0')); // 输入框价钱
        if ($start_price && $end_price) $price = $start_price . '-' . $end_price; // 如果输入框有价钱 
        $filter_param['id'] = $id; //加入帅选条件中      

        $price && ($filter_param['price'] = $price); //加入帅选条件中 

        $goodsLogic = new SaleLogic(); // 前台商品操作逻辑类
        // 分类菜单显示
        $goodsCate = M('sale_cate')->where("id", $id)->find();// 当前分类
        //($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆        
        $cateArr = $goodsLogic->get_goods_cate($goodsCate);
        $goods_category = M('sale_cate')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); // 键值分类数组
        $cat_id_arr = getCatGrandsons($id);
        $goods_where = array(
            'is_on_sale' => 1,  //是否上架
            'catid' =>  ['in', $cat_id_arr],
            'state' => 1
        );
        $filter_goods_id = Db::name('sale')->where($goods_where)->cache(true)->getField("id", true);
        // 过滤帅选的结果集里面找商品        
        if ($price)// 品牌或者价格
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($price); // 根据 品牌 或者 价格范围 查找所有商品id
/*        print_r($goods_id_1);die;*/
            $filter_goods_id = array_intersect($filter_goods_id, $goods_id_1); // 获取多个帅选条件的结果 的交集
        }
        
        $filter_menu = $goodsLogic->get_filter_menu($filter_param, 'search'); // 获取显示的帅选菜单
        $filter_price = $goodsLogic->get_filter_price($filter_goods_id, $filter_param, 'goodsList'); // 帅选的价格期间
        $count = count($filter_goods_id);
        $page = new Page($count, 20);
        if ($count > 0) {
            $goods_list = M('sale')->where("id", "in", implode(',', $filter_goods_id))->order([$sort => $sort_asc])->limit($page->firstRow . ',' . $page->listRows)->select();
            $filter_goods_id2 = get_arr_column($goods_list, 'id');
            if ($filter_goods_id2)
                $goods_images = M('sale_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->cache(true)->select();
        }

        $navigate_cat = navigate_goods_sale($id); // 面包屑导航       
        $this->assign('filter_menu', $filter_menu);  // 帅选菜单
        $this->assign('navigate_cat', $navigate_cat);
        $this->assign('goodsCate', $goodsCate);
        $this->assign('filter_param', $filter_param); // 帅选条件
        $this->assign('goods_list', $goods_list); 
        $this->assign('goods_images', $goods_images);  // 相册图片
        $this->assign('goods_category', $goods_category);
        $this->assign('cateArr', $cateArr);
        $this->assign('filter_price', $filter_price);// 帅选的价格期间
        $this->assign('cat_id', $id);
        $this->assign('page', $page);// 赋值分页输出
        return $this->fetch();
    }

     /**
     * 搜索商品列表页
     */
    public function search()
    {

    	$key = md5($_SERVER['REQUEST_URI'] . I('start_price') . '_' . I('end_price'));
        $html = S($key);
        if (!empty($html)) {
            return $html;
        }

        $filter_param = array(); // 帅选数组    
        $id = I('get.id/d',0); // 当前分类id
        $price = I('get.price', ''); // 价钱
        $sort = I('sort', 'sort'); // 排序
        $sort_asc = I('sort_asc', 'desc'); // 排序
        $start_price = trim(I('post.start_price', '0')); // 输入框价钱
        $end_price = trim(I('post.end_price', '0')); // 输入框价钱
        if ($start_price && $end_price) $price = $start_price . '-' . $end_price; // 如果输入框有价钱 
        $q = urldecode(trim(I('q', ''))); // 关键字搜索
        empty($q) && $this->error('请输入搜索词');
        $filter_param['id'] = $id; //加入帅选条件中      

        $price && ($filter_param['price'] = $price); //加入帅选条件中 
        $q && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        $goodsLogic = new SaleLogic(); // 前台商品操作逻辑类
        $SearchWordLogic = new SearchWordLogic();
        $where = $SearchWordLogic->getSearchWordWheres($q);
        $where['is_on_sale'] = 1;
        $where['state'] = 1;
        Db::name('search_word')->where('keywords', $q)->setInc('search_num');
        $goodsHaveSearchWord = Db::name('sale')->where($where)->count();
        if($goodsHaveSearchWord){
        	$SearchWordIsHave = Db::name('search_word')->where('keywords', $q)->find();
            if ($SearchWordIsHave) {
                Db::name('search_word')->where('id', $SearchWordIsHave['id'])->update(['goods_num' => $goodsHaveSearchWord]);
            } else {
                $SearchWordData = [
                    'keywords' => $q,
                    'pinyin_full' => $SearchWordLogic->getPinyinFull($q),
                    'pinyin_simple' => $SearchWordLogic->getPinyinSimple($q),
                    'search_num' => 1,
                    'goods_num' => $goodsHaveSearchWord
                ];
                Db::name('search_word')->insert($SearchWordData);
            }
        }
        if ($id) {
            $cat_id_arr = getCatGrandsons($id);
            $where['catid'] = array('in', implode(',', $cat_id_arr));
        }
        $search_goods = M('sale')->where($where)->getField('id,catid');
        $filter_goods_id = array_keys($search_goods);
        $filter_cat_id = array_unique($search_goods); // 分类需要去重
        if ($filter_cat_id) {
            $cateArr = M('sale_cate')->where("id", "in", implode(',', $filter_cat_id))->select();
            $tmp = $filter_param;
            foreach ($cateArr as $k => $v) {
                $tmp['id'] = $v['id'];
                $cateArr[$k]['href'] = U("/Home/sale/search", $tmp);
            }
        }

        // 过滤帅选的结果集里面找商品        
        if ($price)// 品牌或者价格
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($price); // 根据 品牌 或者 价格范围 查找所有商品id
            $filter_goods_id = array_intersect($filter_goods_id, $goods_id_1); // 获取多个帅选条件的结果 的交集
        }
        
        $filter_menu = $goodsLogic->get_filter_menu($filter_param, 'search'); // 获取显示的帅选菜单
        $filter_price = $goodsLogic->get_filter_price($filter_goods_id, $filter_param, 'search'); // 帅选的价格期间

        $count = count($filter_goods_id);
        $page = new Page($count, 20);
        if ($count > 0) {
            $goods_list = M('sale')->where(['is_on_sale' => 1, 'id' => ['in', implode(',', $filter_goods_id)]])->order([$sort => $sort_asc])->limit($page->firstRow . ',' . $page->listRows)->select();
            $filter_goods_id2 = get_arr_column($goods_list, 'id');
            if ($filter_goods_id2)
                $goods_images = M('sale_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->cache(true)->select();
        }

        $this->assign('filter_menu', $filter_menu);  // 帅选菜单
        $this->assign('goods_list', $goods_list); 
        $this->assign('goods_images', $goods_images);  // 相册图片
        $this->assign('cateArr', $cateArr);
        $this->assign('filter_price', $filter_price);// 帅选的价格期间
        $this->assign('cat_id', $id);
        $this->assign('page', $page);// 赋值分页输出
        $this->assign('q', I('q'));
        $this->assign('filter_param', $filter_param); // 帅选条件
        C('TOKEN_ON', false);
        return $this->fetch();
    }
    
    public function goodsid(){
    	if(IS_POST){
    		$this->sale();
    		$data['id'] =  I('post.goods_id');
            $order = M('sale')->field('uname,now_price,uid')->where($data)->find();
            if($order['uid'] != ""){
            	$msg = $order['uname'].'拍卖成功,成交价: ￥'.$order['now_price'];
            	$this->ajaxReturn(['status' => 1, 'msg' => $msg]); 
            }else{
            	$this->ajaxReturn(['status' => 1, 'msg' => '拍卖活动结束']); 
            }
    	}
    }

    /*拍卖保证金*/
    public function sale()
    {
    	$time = time();
    	$res  = M('sale')->field('starttime,endtime,id,uids,order_id')->select();
    	foreach ($res as $key => $value) {
    		/*//正在进行中
    		if($time >= $value['starttime'] && $time <= $value['endtime']){
    			dump($value['id']);
    		}*/
    		//已经结束
    		if($time > $value['endtime']){
    			$cash = $this->cash($value['id']);
    			if($value['uids']){
    				$arrs = $this->returno($value['order_id']);
    				$arr = $this->returnm($value['id'], $value['uids']);
    			}
    		}
    	}
    }

    public function returno($orderid)
    {
        $data['id'] = $orderid;
        $res = M('sale_order')->where($data)->select();
        foreach ($res as $key => $value) {
            if($value['salestate'] != 1){ 
                $datas['salestate'] = 1;
                $info = M('sale_order')->where('id',$value['id'])->update($datas);
            }
        }
    }

    public function returnm($goods_id,$uid)
    {
        $data['goods_id'] = $goods_id;
		$data['uid'] = $uid;
		$data['state'] = 1;
		$info = M('cash')->where($data)->select();
		foreach ($info as $key => $value) {
			if($value['salestate'] == 1){
				$ca['salestate'] = 0;
                $infos = M('cash')->where('id',$value['id'])->update($ca);
	            if($infos){
	            	$moneys = M('users')->where('user_id',$value['uid'])->setDec('user_money',$value['money']);
	            }
			}
		}

    }

    public function cash($goods_id)
    {
        $msg['goods_id'] = $goods_id;
        $msg['state'] = 1;
        $msg['salestate'] = 0;
        $res = M('cash')->where($msg)->select();
        foreach ($res as $key => $value) {
        	$data['salestate'] = 1;
            $info = M('cash')->where('id',$value['id'])->update($data);
            if($info){
            	$moneys = M('users')->where('user_id',$value['uid'])->setInc('user_money',$value['money']);
            }
        }
    }
}